import QS from 'qs';
import axios from './apiConfig';
//import { ElMessage } from "element-plus";
//import router from "@/router/index";
export const $Axios = new axios();
class API {
  get baseUrl() {
    return $Axios.instance.defaults.baseURL;
  }

  //请求成功函数
  handleApiFn(data: any) {
    // console.log('data', data);

    // 有的接口没有code
    if (data.code === undefined) {
      return Promise.resolve(data);
    }
    if (
      data.code === 200 ||
      data.code === 205 ||
      data.code === 201 ||
      data.code === 100 ||
      data.bizCode == 200 ||
      data.code === 505 ||
      data.code === '200'
    ) {
      return Promise.resolve(data);
    } else if (data.code === 0) {
      return Promise.resolve(data);
    } else if (data.code >= 2000 && data.code <= 2010) {
      return Promise.resolve(data);
    } else if (data.code === 1003) {
      uni.showToast({
        title: '登录超时，请重新登录',
        icon: 'none'
      });

      setTimeout(async () => {
        // await uniPush.close();
        // uni.setStorageSync('ADMIN-WEB-USER', '');
        // uni.setStorageSync('ADMIN-WEB-USER-INFO', '');
        //window.location.href = '/login';
        // 需要退出环信：true清除缓存
        // IM.close(true);
        uni.navigateTo({
          url: '/pages/login/login'
        });
      }, 2000);
    } else if (data.code === 1005) {
      return Promise.reject(data); //暂定不给数据
    } else if (data.code === 1006) {
      uni.showToast({
        icon: 'none',
        title: '登录后查询商品'
      });
      uni.navigateTo({
        url: '/pages/login/login'
      });
    } else {
      return Promise.reject(data);
    }
  }
  //请求错误函数
  handleReject({ data, status }: any = {}) {
    const msg = data ? data.msg : status ? status : '网络异常';
    return Promise.reject({ msg });
  }
  //get请求
  async GET(url: string, params: any) {
    try {
      const { data } = await $Axios.instance.get(url, { params });
      return this.handleApiFn(data);
    } catch (err) {
      return this.handleReject(err);
    }
  }
  //post请求
  async POST(url: string, params: any) {
    try {
      const { data } = await $Axios.instance.post(url, QS.stringify(params));
      return this.handleApiFn(data);
    } catch (err) {
      return this.handleReject(err);
    }
  }
  //post请求body传参
  async POSTBody(url: string, params: any) {
    try {
      const { data } = await $Axios.instance({
        url,
        data: params,
        method: 'post',
        headers: { 'Content-type': 'application/json' }
      });
      return this.handleApiFn(data);
    } catch (err) {
      return this.handleReject(err);
    }
  }
  //formdata传参
  async FORM(url: string, params: any) {
    try {
      const { data } = await $Axios.instance({
        url,
        data: params,
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      return this.handleApiFn(data);
    } catch (err) {
      return this.handleReject(err);
    }
  }
}
export default API;
